package com.adinnet.admin.system.controller;

import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.common.shiro.EndecryptUtil;
import com.adinnet.admin.common.shiro.ShiroUtils;
import com.adinnet.admin.organization.service.OrganizationService;
import com.adinnet.admin.school.service.SchoolService;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.admin.system.model.vo.SysUserVo;
import com.adinnet.admin.system.model.SysUser;
import com.adinnet.admin.system.service.SysRoleService;
import com.adinnet.admin.system.service.SysUserService;
import com.adinnet.common.biz.enums.RoleCode;
import com.adinnet.common.utils.StringUtil;
import com.adinnet.core.BaseController;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;

import com.adinnet.core.exception.BizException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author sunjianbo
 * @since 2019-05-17
 */
@Controller
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    private static final String DEFAULT_PSW = "123456";  // 用户默认密码
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private CommonService commonService;


    /**
     * 页面跳转
     * @param model
     * @return
     */
    @RequiresPermissions("user:view")
    @RequestMapping
    public String user(Model model) {
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        model.addAttribute("roles", sysRoleService.getListByUserRole(sysUserInfo));
        model.addAttribute("organizations", organizationService.getListByUserRole(sysUserInfo));
        model.addAttribute("schools", schoolService.getListByUserRole(sysUserInfo));
        model.addAttribute("schoolRoleId", sysRoleService.getRoleByRoleCode(RoleCode.SCHOOL.getCode()).getId());
        model.addAttribute("organizationRoleId", sysRoleService.getRoleByRoleCode(RoleCode.ORGANIZATION.getCode()).getId());
        model.addAttribute("classRoleId", sysRoleService.getRoleByRoleCode(RoleCode.CLASSS.getCode()).getId());
        return "system/user.html";
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions("user:view")
    @ResponseBody
    @RequestMapping("/list")
    public PageResult<SysUserVo> list(Integer page, Integer limit, String searchKey, String searchValue,Integer roleId) {
        return sysUserService.listUser(page, limit, searchKey, searchValue,roleId);
    }

    /**
     * 添加用户
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/add")
    public JsonResult add(SysUserVo user, String roleIds, HttpServletRequest request) {
        if(StringUtil.isBlank(user.getNewPwd())){
            return error("请输入密码");//添加用户密码必填
        }
        user.setPassword(EndecryptUtil.encrytMd5(user.getNewPwd(), 3));
        if (sysUserService.add(user, getRoleIds(roleIds))) {
            commonService.saveOperation(request,"账号管理-添加");
            return ok("添加成功，初始密码为" + user.getNewPwd());
        } else {
            return error("添加失败");
        }
    }

    /**
     * 修改用户
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(SysUserVo user, String roleIds, HttpServletRequest request) {
        if(!StringUtil.isBlank(user.getNewPwd())){
            user.setPassword(EndecryptUtil.encrytMd5(user.getNewPwd(), 3));//修改用户:密码非必填;
        }
        if (sysUserService.update(user, getRoleIds(roleIds))) {
            commonService.saveOperation(request,"账号管理-修改");
            return ok("修改成功");
        } else {
            return error("修改失败");
        }
    }

    // 用逗号分割角色
    private List<Integer> getRoleIds(String rolesStr) {
        List<Integer> roleIds = new ArrayList<>();
        if (rolesStr != null) {
            String[] split = rolesStr.split(",");
            for (String t : split) {
                try {
                    roleIds.add(Integer.parseInt(t));
                } catch (Exception e) {
                }
            }
        }
        return roleIds;
    }

    /**
     * 修改用户状态
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/updateState")
    public JsonResult updateState(Integer userId, Integer state, HttpServletRequest request) {
        if (userId == null) {
            return error("参数userId不能为空");
        }
        if (state == null || (state != 0 && state != 1)) {
            return error("状态值不正确");
        }
        SysUser user = new SysUser();
        user.setId(userId);
        user.setStatus(state);
        if (sysUserService.updateById(user)) {
            commonService.saveOperation(request,"账号管理-修改用户状态");
            return ok();
        } else {
            return error();
        }
    }

    /**
     * 删除用户
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/delete")
    public JsonResult delete(Integer userId, HttpServletRequest request) {
        if (userId == null) {
            return error("参数userId不能为空");
        }
//        SysUser user = new SysUser();
//        user.setId(userId);
//        user.setDeleted(true);
//        if (sysUserService.updateById(user)) {
        if (sysUserService.removeById(userId)) {
            commonService.saveOperation(request,"账号管理-修改用户");
            return ok("删除成功");
        } else {
            return error("删除失败");
        }
    }

    /**
     * 重置密码
     **/
    @RequiresPermissions("user:update")
    @ResponseBody
    @RequestMapping("/restPsw")
    public JsonResult resetPsw(Integer userId, HttpServletRequest request) {
        if (userId == null) {
            return error("参数userId不能为空");
        }
        SysUser user = new SysUser();
        user.setId(userId);
        user.setPassword(EndecryptUtil.encrytMd5(DEFAULT_PSW, 3));
        if (sysUserService.updateById(user)) {
            commonService.saveOperation(request,"账号管理-重置密码");
            return ok("重置成功，初始密码为" + DEFAULT_PSW);
        } else {
            return error("重置失败");
        }
    }

    /**
     * 修改自己密码
     **/
    @ResponseBody
    @RequestMapping("/updatePsw")
    public JsonResult updatePsw(String oldPsw, String newPsw, HttpServletRequest request) {
        if (StringUtil.isBlank(oldPsw, newPsw)) {
            return error("参数不能为空");
        }
        if (ShiroUtils.getLoginUser() == null) {
            return error("未登录");
        }
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        if(sysUserInfo==null){
            return error(401,"登录已过期");
        }
        if (!sysUserInfo.getPassword().equals(oldPsw)) {
            return error("原始密码错误");
        }
        SysUser user = new SysUser();
        user.setId(sysUserInfo.getId());
        user.setPassword(EndecryptUtil.encrytMd5(newPsw, 3));
        if (sysUserService.updateById(user)) {
            commonService.saveOperation(request,"修改密码");
            return ok("修改成功");
        } else {
            return error("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/getListByOrganizationId")
    public List<SysUser> getListByOrganizationId(Integer organizationId) {
        return sysUserService.getListByOrganizationId(organizationId);
    }
}
